package com.cyj.dream.core.util.ip;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

/**
 * @Description: 根据ip获取地址
 * @BelongsProject: DreamChardonnay
 * @BelongsPackage: com.cyj.dream.core.util.ip
 * @Author: ChenYongJia
 * @CreateTime: 2021-09-26 11:31
 * @Email: chen87647213@163.com
 * @Version: 1.0
 */
@Slf4j
public class IpToAddressUtil {

    private static final String KEY = "AVFBZ-T2RCP-M26DB-V3C36-LAMOJ-7TBL4";

    /**
     * 使用腾讯的接口通过ip拿到城市信息
     *
     * @param ip
     * @return
     */
    public static StringBuffer getCityInfo(String ip) {
        String s = sendGet(ip, KEY);
        Map map = JSONObject.parseObject(s, Map.class);
        String message = (String) map.get("message");
        String ok = "query ok";
        if (ok.equals(message)) {
            Map result = (Map) map.get("result");
            Map addressInfo = (Map) result.get("ad_info");
            StringBuffer address = new StringBuffer();
            // 国家
            address.append(addressInfo.get("nation"));
            // 省份
            if (!StrUtil.isEmpty(addressInfo.get("province").toString())) {
                address.append("-" + addressInfo.get("province"));
            }
            // 城市
            if (!StrUtil.isEmpty(addressInfo.get("city").toString())) {
                address.append("-" + addressInfo.get("city"));
            }
            // 区
            if (!StrUtil.isEmpty(addressInfo.get("district").toString())) {
                address.append("-" + addressInfo.get("district"));
            }
            // 邮编
            if (!StrUtil.isEmpty(addressInfo.get("adcode").toString())) {
                address.append("-" + addressInfo.get("adcode").toString());
            }
            return address;
        } else {
            System.out.println(message);
            return null;
        }
    }

    /**
     * 根据在腾讯位置服务上申请的key进行请求操作
     *
     * @param ip
     * @param key
     * @return
     */
    public static String sendGet(String ip, String key) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = "https://apis.map.qq.com/ws/location/v1/ip?ip=" + ip + "&key=" + key;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();

            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 测试获取地址方法运行
     *
     * @param args
     */
    public static void main(String[] args) {
        StringBuffer address = IpToAddressUtil.getCityInfo("112.65.61.198");
        System.out.println(address);
    }

}